package com.hugang.socket.tcp;

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP网络编程：
 * 例子1：实现客户端发送信息到服务端，服务端将数据打印到控制台
 *
 * @author hg
 * @date 2020/6/22 15:19
 */
public class TcpTest {

    /**
     * 客户端
     */
    @Test
    public void client() throws IOException {
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        //1、创建Socket对象，指明服务器端的ip和端口号
        Socket socket = new Socket(inetAddress, 3000);
        //2、获取一个输出流用于输出数据
        OutputStream outputStream = socket.getOutputStream();
        //3、写出数据
        outputStream.write("socket编程111".getBytes());

        //4、资源关闭
        outputStream.close();
        socket.close();
    }

    /**
     * 服务端
     *
     * @throws IOException
     */
    @Test
    public void server() throws IOException {
        //1、创建服务器端的ServerSocket，指明监听的端口号
        ServerSocket serverSocket = new ServerSocket(3000);
        //2、调用accept()表示接收来自客户端的socket
        Socket accept = serverSocket.accept();
        //3、获取输入流
        InputStream inputStream = accept.getInputStream();

        //不建议，可能会有乱码
//        int len;
//        byte[] bytes = new byte[5];
//        while ((len = inputStream.read(bytes)) != -1) {
//            System.out.println(new String(bytes, 0, len));
//        }
        //4、读取输入流中的数据
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int len;
        byte[] bytes = new byte[5];
        while ((len = inputStream.read(bytes)) != -1) {
            byteArrayOutputStream.write(bytes,0,len);
        }
        System.out.println(byteArrayOutputStream.toString());

        System.out.println(accept.getInetAddress());

        //5、资源关闭
        byteArrayOutputStream.close();
        inputStream.close();
        accept.close();
        serverSocket.close();

    }
}
